/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.kofigyan.stateprogressbar.utils;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.ScaleMode;
import ohos.media.image.common.Size;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PixelMapUtils {

    /**
     * 对PixelMap进行压缩
     *
     * @param pixelMap
     * @param compressFormat
     * @param quality
     * @param outputStream
     * @return
     */
    public static boolean compress(PixelMap pixelMap, String compressFormat, int quality, OutputStream outputStream) {
        if (pixelMap == null) {
            return false;
        }
        ImagePacker imagePacker = ImagePacker.create();
        ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
        packingOptions.format = compressFormat;
        packingOptions.quality = quality;
        boolean result = imagePacker.initializePacking(outputStream, packingOptions);
        if (result) {
            imagePacker.addImage(pixelMap);
            imagePacker.finalizePacking();
            return true;
        } else {
            return false;
        }
    }

    public static PixelMap createBitmap(int width, int height, PixelFormat pixelFormat) {
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(width, height);
        initializationOptions.pixelFormat = pixelFormat;
        initializationOptions.editable = true;
        return PixelMap.create(initializationOptions);
    }

    public static PixelMap createBitmap(PixelMap source, int x, int y, int width, int height,
                                          Matrix matrix, boolean filter) {
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();

        RectFloat srcR = new RectFloat(x, y, x + width,y + height);
        RectFloat dstR = new RectFloat(0, 0, width, height);
        RectFloat deviceR = new RectFloat();
        Paint paint = new Paint();
        paint.setFilterBitmap(filter);
        if (matrix != null) {
            final boolean transformed = !matrix.rectStaysRect();
            if (transformed) {
                paint.setAntiAlias(true);
            }
            matrix.mapRect(deviceR, dstR);
        } else {
            deviceR = dstR;
        }

        int neww = Math.round(deviceR.getWidth());
        int newh = Math.round(deviceR.getHeight());
        initializationOptions.size = new Size(neww,newh);
        initializationOptions.scaleMode = ScaleMode.CENTER_CROP;
//        initializationOptions.alphaType = AlphaType.OPAQUE;
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        PixelMap srcPixelMap = PixelMap.create(initializationOptions);
        Texture texture = new Texture(srcPixelMap);
        Canvas canvas = new Canvas(texture);

        canvas.translate(-deviceR.left, -deviceR.top);
        canvas.concat(matrix);
        canvas.drawPixelMapHolderRect(new PixelMapHolder(source), srcR, dstR, paint);
        return texture.getPixelMap();
    }

    public static PixelMap getPixelMapFromResource(Context context, int resourceId) {
        InputStream inputStream = null;
        try {

            // 创建图像数据源ImageSource对象
            inputStream = context.getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/jpg";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);
            // 设置图片参数
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            return imageSource.createPixelmap(decodingOptions);
        } catch (IOException e) {
//            HiLogUtil.showLog("ImageUtils", "IOException");
        } catch (NotExistException e) {
//            HiLogUtil.showLog("ImageUtils", "NotExistException");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
//                    HiLogUtil.showLog("ImageUtils", "inputStream IOException");
                }
            }
        }
        return null;
    }

    public static PixelMap createScaledBitmap(PixelMap src,
                                              int dstWidth,
                                              int dstHeight,
                                              boolean filter) {
        Matrix m = new Matrix();

        final int width = src.getImageInfo().size.width;
        final int height = src.getImageInfo().size.height;
        if (width != dstWidth || height != dstHeight) {
            final float sx = dstWidth / (float) width;
            final float sy = dstHeight / (float) height;
            m.setScale(sx, sy);
        }
        return createBitmap(src, 0, 0, width, height, m, filter);
    }
}
